package com.huilan.etl.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * bean转map
 * 2014年12月8日 下午4:59:19
 * @author CheWenliang
 */
public class BeanToMap {
	
	private static Logger log = LoggerFactory.getLogger(BeanToMap.class);
	
	/**
	 * 将bean对象转换为map
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> transBean2Map(Object obj) {
		return transBean2Map(obj, null);
    }
	
	/**
	 * 将bean对象转换为map
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> transBean2Map(Object obj, PropertyFilter filter){
		Map<String, Object> map = new HashMap<String, Object>();
		if(obj == null){
			return map;
		}
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class")) {
                	// 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                	if(filter == null || filter.apply(obj, key, value)){
                		map.put(key, getter.invoke(obj));
                	}
                }

            }
        } catch (Exception e) {
			e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return map;
	}
	
	/**
	 * property属性过滤器
	 * @author CheWenliang
	 *
	 */
	public interface PropertyFilter{
		public boolean apply(Object source, String name, Object value);
	}
	
	public static void main(String[] args) {
	}
}
